package com.ruoyi.predict.controller;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.predict.service.PredictByHuaWeiService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;

import java.time.Duration;
import java.util.Collections;

import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.predict.domain.BoleScriptPredictionRecord;
import com.ruoyi.predict.service.IPredictionService;

/**
 * 预测控制器
 *
 * @author assistant
 * @date 2024-07-12
 */
@RestController
@RequestMapping("/predict")
public class PredictionController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PredictionController.class);

    @Autowired
    private IPredictionService predictionService;
    @Autowired
    private PredictByHuaWeiService predict;

    @PostMapping("/predictJob")
    public AjaxResult predictJob() throws InterruptedException {
        predict.executePrediction(SecurityUtils.getUserId());
        Thread.sleep(3000);
        predict.executeResumeAnalysis(SecurityUtils.getUserId());
        return AjaxResult.success("");
    }
    /**
     * 调用预测脚本进行岗位预测
     */
//    @PreAuthorize("@ss.hasPermi('predict:script:call')")
    @Log(title = "岗位预测", businessType = BusinessType.OTHER)
    @PostMapping("/callPrediction")
    public AjaxResult callPrediction(  @RequestParam("predictionPrompt")String predictionPrompt) {
        try {
            // 配置 Ollama 连接（本地部署的 Qwen 模型）
            OllamaChatModel model = OllamaChatModel.builder()
                    .baseUrl("http://www.bigpigbig.cn:11434") // 注意这里去掉了/api/chat部分
                    .modelName("qwen:1.8b") // 确保模型名称与服务器上的一致
                    .temperature(0.1) // 通常温度值在0-1之间
                    .timeout(Duration.ofSeconds(120))
                    .numPredict(300)  // 最大生成 tokens
//                    .stop(Collections.singletonList("</s>"))
                    .build();

            // 构建预测提示
//            String predictionPrompt = buildPredictionPrompt();

            // 构建用户消息
            ChatMessage userMessage = UserMessage.from(predictionPrompt);

            // 调用模型生成预测结果
            String predictionResult = String.valueOf(model.generate(Collections.singletonList(userMessage))
                    .content());

            System.out.println(predictionResult);

            return success(predictionResult);
        } catch (Exception e) {
            logger.error("岗位预测失败", e);
            return error("岗位预测失败：" + e.getMessage());
        }
    }

    /**
     * 构建预测提示
     */
    private String buildPredictionPrompt() {
        String predictionPrompt = "根据简历预测岗位，严格遵守以下规则：" +
                "1. 仅返回JSON，无任何前缀、后缀、解释文字；" +
                "2. JSON结构必须为：{\"jobs\":[{\"name\":\"岗位名\",\"reason\":\"理由\"}]}；" +
                "3. 确保JSON格式正确，无语法错误。\n" +
                "简历：5年Java开发，Spring Boot微服务Redis，电商高并发项目经验。";
        return predictionPrompt;
    }

}
